#pragma once
#include <iostream>
#include <pthread.h>

namespace LockModule
{
    class Mutex
    {
        Mutex(const Mutex &) = delete;
        const Mutex &operator=(const Mutex &) = delete;

    public:
        Mutex()
        {
            int n = pthread_mutex_init(&_lock, nullptr); // 初始化锁
            (void)n;                                     // 防止报警告
        }

        // 上锁
        void Lock()
        {
            int n = pthread_mutex_lock(&_lock);
            (void)n;
        }

        // 返回锁指针
        pthread_mutex_t *LockPtr()
        {
            return &_lock;
        }

        // 解锁
        void Unlock()
        {
            int n = pthread_mutex_unlock(&_lock);
            (void)n;
        }

        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_lock);
            (void)n;
        }

    private:
        pthread_mutex_t _lock;
    };

    //二次封装 -- 这样可以不用解锁了
    class LockGuard
    {
    public:
        LockGuard(Mutex &mtx):_mtx(mtx)
        {
            _mtx.Lock();
        }
        ~LockGuard()
        {
            _mtx.Unlock();
        }
    private:
        Mutex &_mtx;
    };

}

